from flask import request, jsonify, current_app
import os
from flask_jwt_extended import jwt_required, get_jwt_identity
from sqlalchemy import desc, or_

from backend.infrastructure.database import db
from backend.models.user import User
from backend.models.student import Student
from backend.models.medical_consult import MedicalConsult, ConsultAttachment, ConsultCategory
from backend.services.unified_log_service import log_service
from backend.config.upload_config import UploadConfig
from backend.services.media_service import MediaService
from . import miniprogram_bp


@miniprogram_bp.route('/communication/consults', methods=['GET'])
@jwt_required()
def get_consults():
    """获取咨询记录列表"""
    try:
        current_user_id = int(get_jwt_identity())
        
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        consult_type = request.args.get('type', 'my_consults')
        
        # 构建查询
        query = MedicalConsult.query.filter(
            MedicalConsult.user_id == current_user_id
        )
        
        if consult_type == 'doctor_replies':
            # 只显示有医生回复的记录
            query = query.filter(MedicalConsult.status == 'replied')
        elif consult_type == 'my_consults':
            # 显示所有我的咨询
            pass
        
        # 分页查询
        pagination = query.order_by(desc(MedicalConsult.created_at)).paginate(
            page=page,
            per_page=per_page,
            error_out=False
        )
        
        consults = [consult.to_dict() for consult in pagination.items]
        
        return jsonify({
            'success': True,
            'data': {
                'consults': consults,
                'pagination': {
                    'page': page,
                    'per_page': per_page,
                    'total': pagination.total,
                    'pages': pagination.pages,
                    'has_next': pagination.has_next,
                    'has_prev': pagination.has_prev
                }
            }
        })
        
    except Exception as e:
        current_app.logger.error(f'获取咨询记录失败: {str(e)}')
        return jsonify({'success': False, 'message': '获取咨询记录失败'}), 500


@miniprogram_bp.route('/communication/consults', methods=['POST'])
@jwt_required()
def create_consult():
    """创建新咨询"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        # 验证必需字段
        required_fields = ['title', 'content', 'category']
        for field in required_fields:
            if not data.get(field):
                return jsonify({'success': False, 'message': f'缺少必需字段: {field}'}), 400
        
        # 获取用户绑定的学生信息
        user = User.query.get(current_user_id)
        if not user:
            return jsonify({'success': False, 'message': '用户不存在'}), 404
        
        # 获取用户绑定的学生ID
        student_id = user.student_id if user.student_id else None
        
        # 创建咨询记录
        consult = MedicalConsult(
            user_id=current_user_id,
            student_id=student_id,
            title=data['title'].strip(),
            content=data['content'].strip(),
            category=data['category'],
            priority=data.get('priority', 'normal'),
            images=data.get('images', [])
        )
        
        db.session.add(consult)
        db.session.commit()
        
        # 记录操作日志
        log_service.log_operation(
            user_id=current_user_id,
            action='CREATE',
            table_name='medical_consults',
            record_id=consult.id,
            details=f'创建医生咨询: {consult.title}'
        )
        
        return jsonify({
            'success': True,
            'message': '咨询提交成功',
            'data': {
                'id': consult.id,
                'title': consult.title,
                'category': consult.category,
                'priority': consult.priority,
                'status': consult.status
            }
        })
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'创建咨询失败: {str(e)}')
        current_app.logger.error(f'错误详情: {repr(e)}')
        import traceback
        current_app.logger.error(f'错误堆栈: {traceback.format_exc()}')
        return jsonify({'success': False, 'message': '创建咨询失败'}), 500


@miniprogram_bp.route('/communication/consults/<int:consult_id>', methods=['GET'])
@jwt_required()
def get_consult_detail(consult_id):
    """获取咨询详情"""
    try:
        current_user_id = int(get_jwt_identity())
        
        consult = MedicalConsult.query.filter(
            MedicalConsult.id == consult_id,
            MedicalConsult.user_id == current_user_id
        ).first()
        
        if not consult:
            return jsonify({'success': False, 'message': '咨询记录不存在'}), 404
        
        return jsonify({
            'success': True,
            'data': consult.to_dict()
        })
        
    except Exception as e:
        current_app.logger.error(f'获取咨询详情失败: {str(e)}')
        return jsonify({'success': False, 'message': '获取咨询详情失败'}), 500


@miniprogram_bp.route('/communication/consults/<int:consult_id>/close', methods=['POST'])
@jwt_required()
def close_consult(consult_id):
    """关闭咨询"""
    try:
        current_user_id = int(get_jwt_identity())
        
        consult = MedicalConsult.query.filter(
            MedicalConsult.id == consult_id,
            MedicalConsult.user_id == current_user_id
        ).first()
        
        if not consult:
            return jsonify({'success': False, 'message': '咨询记录不存在'}), 404
        
        if consult.status == 'closed':
            return jsonify({'success': False, 'message': '咨询已关闭'}), 400
        
        consult.status = 'closed'
        db.session.commit()
        
        # 记录操作日志
        log_service.log_operation(
            user_id=current_user_id,
            action='UPDATE',
            table_name='medical_consults',
            record_id=consult.id,
            details=f'关闭咨询: {consult.title}'
        )
        
        return jsonify({
            'success': True,
            'message': '咨询已关闭'
        })
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'关闭咨询失败: {str(e)}')
        return jsonify({'success': False, 'message': '关闭咨询失败'}), 500


@miniprogram_bp.route('/communication/categories', methods=['GET'])
@jwt_required()
def get_consult_categories():
    """获取咨询分类"""
    try:
        categories = [
            {'value': 'vision_check', 'label': '视力检查'},
            {'value': 'intervention', 'label': '干预咨询'},
            {'value': 'symptoms', 'label': '症状询问'},
            {'value': 'treatment', 'label': '治疗方案'},
            {'value': 'prevention', 'label': '预防建议'},
            {'value': 'other', 'label': '其他问题'}
        ]
        
        return jsonify({
            'success': True,
            'data': {'categories': categories}
        })
        
    except Exception as e:
        current_app.logger.error(f'获取咨询分类失败: {str(e)}')
        return jsonify({'success': False, 'message': '获取咨询分类失败'}), 500


"""(已移除) 上传图片接口: 统一迁移至 upload_api.py /api/miniprogram/upload/image
开发阶段禁止兜底：任何仍调用旧路径的前端将收到 404/405 直接暴露问题。
"""
